from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV

# 加载鸢尾花数据集并划分数据集 (代码省略)
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化随机森林分类器
model = RandomForestClassifier(random_state=42)

# 定义超参数网格，要搜索的超参数及其取值范围
param_grid = {
    'n_estimators': [50, 100, 150, 200], # 决策树数量
    'max_depth': [5, 10, 15, None],      # 决策树最大深度
    'min_samples_split': [2, 5, 10]      # 节点分裂所需的最小样本数
}

# 初始化 GridSearchCV，cv=3 表示 3 折交叉验证
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=3, scoring='accuracy', n_jobs=-1)
# 使用训练集进行网格搜索和模型训练
grid_search.fit(X_train, y_train)

# 获取最佳模型
best_model = grid_search.best_estimator_
# 获取最佳超参数组合
best_params = grid_search.best_params_
# 获取最佳交叉验证分数
best_score = grid_search.best_score_

print("最佳模型:\n", best_model)
print("\n最佳超参数:", best_params)
print("\n最佳交叉验证准确率:", best_score)

# 使用最佳模型在测试集上评估性能
test_accuracy = best_model.score(X_test, y_test)
print("\n最佳模型在测试集上的准确率:", test_accuracy)